#set(notfmt='@formatter:off')
#set(generatorConfig = detail.toGeneratorConfig())
#set(template = generatorConfig.template ?? template)
#set(tables = generatorConfig.tables)
#set(isStepNav = isStepNav??false)
#set(releaseFieldsList = generatorConfig.releaseFieldsList)
<form class="layui-form detail_form form-table-edit" action="" lay-filter="generator_model-edit-form">
    <input type="hidden" name="generator_id" value="#(detail.generator_id)">

    <div class="layui-form-item">
        <label class="layui-form-label">生成器名称</label>
        <div class="layui-input-block">
            <input type="text" name="generator_name" value="#(detail.generator_name)" lay-verify="required" placeholder="请输入生成器名称" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">访问URI</label>
        <div class="layui-input-block">
            <input type="text" name="controller_uri" value="#(generatorConfig.ctlUri)" lay-verify="required" placeholder="请输入访问URI" class="layui-input" autocomplete="off">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">代码包名</label>
        <div class="layui-input-block">
            <input type="text" name="code_package" value="#(generatorConfig.packagePath)" lay-verify="required" placeholder="请输入代码包名" class="layui-input" autocomplete="off">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">模板选择</label>
        <div class="layui-input-block">
            <select id="template_select" name="template_select" lay-verify="" xm-select-search="" xm-select-radio=""
                    placeholder="选择代码生成模板" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="template_select" lay-filter="template_select">
                <option value="">选择代码生成模板</option>
            </select>
        </div>
    </div>

    <div id="temp_param_config">
    </div>

    <div id="config_dyn_area" class="table_config_area">

    </div>
    <div id="table_release_dyn_area" class="table_config_area">

    </div>

    <div class="detail_form_footer">
        <a class="layui-btn" lay-submit lay-filter="btn-generator_model-submit">保存</a>
        <a class="layui-btn layui-btn-primary" lay-filter="btn-generator_model-cancle">取消</a>
    </div>
</form>

<!-- 模板参数模板 -->
<div id="table_temp_param_config_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">{title}</label>
        <div class="layui-input-inline">
            <input type="text" name="temp_param_{name}" value="{value}" placeholder="请输入{title}" class="layui-input" autocomplete="off">
        </div>
        <div class="layui-form-mid layui-word-aux">{desc}</div>
    </div>
</div>

<!-- 显示名称 -->
<script type="text/html" id="temp_param_value_templet">
    <input type="text" name="param_value_{{d.no}}" value="{{d.value?d.value:''}}" required lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">
</script>


<!-- 表模板 -->
<div id="table_config_area_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">表no</label>
        <div class="layui-input-block">
            <select id="tableno_select" name="tableno" lay-verify="" xm-select-search="" xm-select-radio=""
                    placeholder="选择表no" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="tableno_select" lay-filter="tableno_select">
                <option value="">选择表no</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            <!-- 列表表格 -->
            <table id="tableno_field_list" lay-filter="tableno_field_list" style="width: 100%"></table>
        </div>
    </div>
</div>
<!-- 表关系模板 -->
<div id="table_release_config_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">表关联</label>
        <div class="layui-input-block">
            <!-- 列表表格 -->
            <table id="table_release_list_temp" lay-filter="table_release_list_temp" style="width: 100%"></table>
        </div>
    </div>
</div>

<!-- 是否为标题字段 -->
<script type="text/html" id="is_title_templet">
    <input type="radio" name="title_{{d.tableNo}}" lay-verify="required" value="{{d.field_id}}" {{d.isTitle?'checked':''}} title="" lay-skin="primary">
</script>
<!-- 是否在编辑页面显示 -->
<script type="text/html" id="show_in_form_templet">
    <input type="checkbox" name="show_in_form_{{d.tableNo}}_{{d.field_id}}" {{d.showInForm?'checked':''}} title="" lay-skin="primary">
</script>
<!-- 必填页面显示 -->
<script type="text/html" id="is_required_templet">
    <input type="checkbox" name="required_{{d.tableNo}}_{{d.field_id}}" {{d.isRequired?'checked':''}} title="" lay-skin="primary">
</script>
<!-- 校验器模板 -->
<script type="text/html" id="checker_templet">
    <div id="checker_{{d.tableNo}}_{{d.field_id}}">
</script>
<!-- 是否在搜索栏显示 -->
<script type="text/html" id="show_in_search_form_templet">
    <input type="checkbox" name="show_in_search_form_{{d.tableNo}}_{{d.field_id}}" {{d.showInSearchForm?'checked':''}} title="" lay-skin="primary">
</script>
<!-- 是否在列表表格中显示 -->
<script type="text/html" id="show_in_list_templet">
    <input type="checkbox" name="show_in_list_{{d.tableNo}}_{{d.field_id}}" {{d.showInList?'checked':''}} title="" lay-skin="primary">
</script>
<script type="text/html" id="release_oper_templet">
    <a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
</script>
<!-- 查询方式 -->
<script type="text/html" id="search_method_templet">
    <select name="search_method_{{d.tableNo}}_{{d.field_id}}" lay-verify="">
        <option value="eq" {{d.searchMethod == "eq"?"selected":""}}>等于</option>
        <option value="noteq" {{d.searchMethod == "noteq"?"selected":""}}>不等于</option>
        <option value="gt" {{d.searchMethod == "gt"?"selected":""}}>大于</option>
        <option value="gteq" {{d.searchMethod == "gteq"?"selected":""}}>大于等于</option>
        <option value="lt" {{d.searchMethod == "lt"?"selected":""}}>小于</option>
        <option value="lteq" {{d.searchMethod == "lteq"?"selected":""}}>小于等于</option>
        <option value="like" {{d.searchMethod == "like"?"selected":""}}>包含文本</option>
        <option value="notlike" {{d.searchMethod == "notlike"?"selected":""}}>不包含文本</option>
        <option value="close_range" {{d.searchMethod == "close_range"?"selected":""}}>区间上(含边界)</option>
        <option value="open_range" {{d.searchMethod == "open_range"?"selected":""}}>区间内(不含边界)</option>
    </select>
</script>
<!-- 表单组件类型 -->
<script type="text/html" id="form_component_templet">
    <select name="form_component_{{d.tableNo}}_{{d.field_id}}" lay-verify="">
        <option value="auto" {{d.formComponent == "auto"?"selected":""}}>自动</option>
        <optgroup label="输入型">
            <option value="text" {{d.formComponent == "text"?"selected":""}}>文本框</option>
            <option value="password" {{d.formComponent == "password"?"selected":""}}>密码框</option>
            <option value="textArea" {{d.formComponent == "textArea"?"selected":""}}>文本域</option>
            <option value="richText" {{d.formComponent == "richText"?"selected":""}}>富文本框</option>
            <option value="datetime" {{d.formComponent == "datetime"?"selected":""}}>日期时间框</option>
            <option value="year" {{d.formComponent == "year"?"selected":""}}>年选择框</option>
            <option value="month" {{d.formComponent == "month"?"selected":""}}>年月选择框</option>
            <option value="date" {{d.formComponent == "date"?"selected":""}}>日期选择框</option>
            <option value="time" {{d.formComponent == "time"?"selected":""}}>时间框</option>
            <option value="integer" {{d.formComponent == "integer"?"selected":""}}>整数框</option>
            <option value="decimal" {{d.formComponent == "decimal"?"selected":""}}>小数框</option>
            <option value="file" {{d.formComponent == "file"?"selected":""}}>文件选择框</option>
            <option value="image" {{d.formComponent == "image"?"selected":""}}>图片选择框</option>
            <option value="avatar" {{d.formComponent == "avatar"?"selected":""}}>头像选择框</option>
            <option value="icon" {{d.formComponent == "icon"?"selected":""}}>图标选择框</option>
        </optgroup>
<!--        <optgroup label="选项型">-->
<!--            <option value="radio" {{d.formComponent == "radio"?"selected":""}}>单选框</option>-->
<!--            <option value="select" {{d.formComponent == "select"?"selected":""}}>下拉框</option>-->
<!--        </optgroup>-->
    </select>
</script>
<!-- 关联字段 -->
<script type="text/html" id="release_field_templet">
    <select name="release_field" lay-verify="">
    </select>
</script>
<div id="release_field_templet_area"></div>

<script>
    layui.use(['admin', 'form', 'laydate', 'formSelects', 'xmSelect'], function () {
        var $ = layui.$
            , admin = layui.admin
            , element = layui.element
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , formSelects = layui.formSelects
            , xmSelect = layui.xmSelect
            , form = layui.form;

        form.render(null, 'generator_model-edit-form');
        let tempList = [];
        let tables = {}
        let tableFields = {}

        let tableCols = [[
            {field: 'field_key', align: 'center', width: 150, title: '字段名', event: 'field_key'},
            {field: 'field_type', align: 'center', width: 100, title: '字段类型', event: 'field_type'},
            {field: 'field_name', align: 'center', width: 150, title: '显示名称', event: 'field_name'},
            {field: 'isTitle', align: 'center', width: 60, title: '标题', event: 'isTitle', templet: "#is_title_templet"},
            {field: 'showInList', align: 'center', width: 60, title: '列表', event: 'showInList', templet: "#show_in_list_templet"},
            {field: 'showInForm', align: 'center', width: 60, title: '编辑', event: 'showInForm', templet: "#show_in_form_templet"},
            {field: 'formComponent',  width: 150, title: '表单控件', event: 'formComponent', templet: "#form_component_templet"},
            {field: 'isRequired', align: 'center', width: 60, title: '必填', event: 'isRequired', templet: "#is_required_templet"},
            {field: 'showInSearchForm', align: 'center', width: 60, title: '查询', event: 'showInSearchForm', templet: "#show_in_search_form_templet"},
            {field: 'searchMethod', align: 'center', width: 150, title: '查询方式', event: 'searchMethod', templet: "#search_method_templet"},
            {field: 'checker', align: 'center', width: 400, title: '表单校验', event: 'checker', templet: "#checker_templet"},
        ]];

        let tableReleaseCols = [[
            {field: 'releaseField1', align: 'center', title: '外键字段', event: 'releaseField1', templet: "#release_field1_templet"},
            {field: 'releaseField2', align: 'center', title: '关联表字段', event: 'releaseField2', templet: "#release_field2_templet"},
            {field: 'releaseOper', align: 'center', title: '操作', event: 'releaseOper', templet: "#release_oper_templet"},
        ]];

        //渲染数据库表下拉选择器
        formSelects.data('template_select', 'server', {
            url: '/generator/template/list',
            keyName: 'template_name',
            keyVal: 'template_id',
            searchName: 'template_name__op__like',
            showPage: true,
            size: 10,
            beforeSuccess: function (id, url, input, res) {
                res.data.forEach(function(item){
                    let isExist = false;
                    for (let tempListElement of tempList) {
                        if(tempListElement.template_id == item.template_id){
                            isExist = true;
                            break;
                        }
                    }
                    if(!isExist){
                        tempList.push(item);
                    }
                })
                return res;
            }
        });

        formSelects.on('template_select', function (id, vals, val, isAdd, isDisabled) {
            if (isAdd) {
                renderTemplateConfig(val.val)
                renderTableConfig(val.val)
            } else {
                renderTemplateConfig(null)
                renderTableConfigArea(0)
            }
            tableFields = [];
            renderTableReleaseConfig();
        }, true);

        function renderTemplateConfig(templateId){
            let rendered = false;
            tempList.forEach(function (temp) {
                if (templateId == temp.template_id) {
                    let config = temp ? temp.template_config : null;
                    config = config ? JSON.parse(config) : [];
                    renderTemplateConfigData(config)
                    rendered = true;
                }
            })
            if(!rendered){
                renderTemplateConfigData([])
            }
        }

        function renderTemplateConfigData(config){
            let html = '';
            config = config&&config.forEach?config:[];
            config.forEach(function(item){
                let $configInput = $('#table_temp_param_config_temp');
                html += $configInput.html()
                    .replace(/\{title\}/g, item.title)
                    .replace(/\{name\}/g, item.name)
                    .replace(/\{value\}/g, item.value)
                    .replace(/\{desc\}/g,item.desc);
            });
            $('#temp_param_config').html(html);
        }

        #if(template != null && template.template_id != null)
            formSelects.value('template_select', ['#(template.template_id)']);
            renderTemplateConfigData(#(template.template_config));
            renderTableConfigArea(#(template.table_require_count));
            var tempFieldList = []
            #if(tables != null && tables.size() > 0)
                #for(table:tables)
                    formSelects.value('table#(for.index+1)_select', ['#(table.table_id)']);
                    let table#(for.index+1)InitValue = #(table.toJson());
                    tempFieldList = []
                    // console.log('table#(for.index+1)InitValue',table#(for.index+1)InitValue)
                    table#(for.index+1)InitValue.fieldModelList.forEach(function (item) {
                        tempFieldList.push({...item.attrs, ...item, attrs: undefined,tableNo: #(for.index+1)})
                    })
                    renderTableFieldTable(#(for.index+1), tempFieldList);
                    tableFields[#(for.index+1)] = tempFieldList;
                #end
            #end
            #if(releaseFieldsList.size()>0)
                renderTableReleaseConfig(#(toJson(releaseFieldsList)));
            #end
        #end
        // 渲染表关联配置
        function renderTableConfig(templateId) {
            tempList.forEach(function (item) {
                if (templateId == item.template_id) {
                    let tableRequireCount = item.table_require_count;
                    renderTableConfigArea(tableRequireCount)
                }
            })
        }

        // 渲染表关联配置区域
        function renderTableConfigArea(tableRequireCount) {
            let newHtml = '';
            for (let idx = 0; idx < tableRequireCount; idx++) { // 复制模板
                let html = $('#table_config_area_temp').clone().html()
                let no = idx + 1;
                newHtml = newHtml + html.replace(/tableno/g, 'table' + no).replace(/表no/g, '表' + no)
            }
            $('#config_dyn_area').html(newHtml);
            // 渲染组件
            form.render(null, 'generator_model-edit-form');
            // 插入模板
            for (let idx = 0; idx < tableRequireCount; idx++) {
                let no = idx + 1;
                //渲染数据库表下拉选择器
                let tableSelectId = 'table' + no + '_select';
                formSelects.data(tableSelectId, 'server', {
                    url: '/generator/table/list',
                    keyName: 'table_name',
                    keyVal: 'table_id',
                    searchName: 'table_name__op__like',
                    showPage: true,
                    beforeSuccess: function (id, url, input, res) {
                        tables[id] = tables[id]?tables[id]:[];
                        res.data.forEach(function(item){
                            let isExist = false;
                            for (let tableItem of tables[id]) {
                                if(tableItem.table_id == item.table_id){
                                    isExist = true;
                                    break;
                                }
                            }
                            if(!isExist){
                                tables[id].push(item);
                            }
                        })
                        return res;
                    },
                    size: 10,
                });

                formSelects.on(tableSelectId, function (id, vals, val, isAdd, isDisabled) {
                    if (isAdd) {
                        loadTableFieldList(val.val, no)
                    } else {
                        delete tableFields[no]
                        renderTableFieldTable(no, []);
                        renderTableReleaseConfig();
                    }
                }, true);

                renderTableFieldTable(no, [])
            }
        }

        function loadTableFieldList(tableId, tableNo) {
            $.ajax({
                method: 'post',
                url: "/generator/field/list",
                data: {table_id: tableId},
                dataType: 'json',
                success: function (rs) {
                    if (rs.success) {
                        let data = rs.data;
                        tableFields[tableNo] = data;
                        let fieldListData = initFieldConfigData(data, tableNo);
                        table.render({
                            id: "table" + tableNo + "_field_list",
                            elem: "#table" + tableNo + "_field_list",
                            data: fieldListData,
                            cols: tableCols,
                            limit: 999,
                        })
                        renderCheckers(fieldListData)
                        renderTableReleaseConfig();
                    } else {
                        layer.msg('请求列表失败!', {icon: 5});
                    }
                },
                error: function (a, b, c) {
                    layer.msg('请求列表异常!', {icon: 5});
                }
            });
        }

        function renderTableFieldTable(tableNo, data) {
            let fieldListData = initFieldConfigData(data, tableNo);
            table.render({
                id: "table" + tableNo + "_field_list",
                elem: "#table" + tableNo + "_field_list",
                data: fieldListData,
                cols: tableCols,
                limit: 999,
            })
            renderCheckers(fieldListData)
        }

        // 渲染值检查器
        function renderCheckers(fields){
            let defaultCheckers = [
                {name: '邮箱', value: /^\w+([-+.]\w+)*@\w+([-.]\w+)*.\w+([-.]\w+)*$/+'【邮箱】'},
                {name: '手机号', value: /^1\d{10}$/+'【手机号】'},
                {name: '中文', value: /^[\u4e00-\u9fa5]{0,}$/+'【中文】'},
                {name: '英文', value: /^[A-Za-z]{0,}$/+'【英文】'},
                {name: '数字', value: /^[0-9]{0,}$/+'【数字】'},
                {name: '英文、数字、下划线', value: /^[A-Za-z0-9_]+$/+'【英文、数字、下划线】'},
                {name: '中文、英文、数字、下划线', value: /^[\u4e00-\u9fa5A-Za-z0-9_]+$/+'【中文、英文、数字、下划线】'},
                {name: '日期时间', value: /^[1-9]\d{3}-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]?\d):[0-5]?\d:[0-5]?\d$/+'【日期时间】'},
                {name: '日期', value: /^\d{4}-\d{1,2}-\d{1,2}/+'【日期】'},
                {name: '时间', value: /^\d{1,2}:\d{1,2}:\d{1,2}/+'【时间】'},
                {name: '身份证', value: /(^\d{8}(0\d|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/ + '【身份证】'},
                {name: '固定电话', value: /^0\d{2,3}-\d{7,8}$/+'【固定电话】'},
                {name: 'URL', value: /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/ + '【URL】'},
                {name: 'IPv4', value: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/+'【IPv4】'},
            ]
            //渲染多选
            fields.forEach(item =>  {
                let checkers = item.checkers || [];
                let newCheckers = JSON.parse(JSON.stringify(defaultCheckers));
                if(checkers&&checkers.length){
                    for(let idx=0;idx<checkers.length;idx++){
                        let isExist = false;
                        let checker = checkers[idx];
                        for(let i = 0; i <newCheckers.length ; i++) {
                            if(newCheckers[i].value == checker){
                                isExist = true;
                                break;
                            }
                        }
                        if(!isExist){
                            var name = checker.match(/.*【(.*?)】/)[1];
                            newCheckers.push({name:name||"自定义",value: checker})
                        }
                    }
                }
                var xm = xmSelect.render({
                    el: '#checker_' + item.tableNo + '_'+item.field_id,
                    name: 'checker_' + item.tableNo + '_'+item.field_id,
                    filterable: true,
                    data: newCheckers,
                    searchTips: '自定义格式：/{正则}/【{标题}】',
                    initValue: checkers,
                    create: function(val, arr){
                        //返回一个创建成功的对象, val是搜索的数据, arr是搜索后的当前页面数据
                        var reg = /(.*?)【(.*?)】/;
                        let match = val.match(reg);
                        if(match&&match.length>2){
                           return {
                               name: match[2],
                               value: val
                           };
                        }else{
                            return {
                                name: val + '【自定义】',
                                value: val + '【自定义】'
                            }
                        }
                    }
                })

                // item.__xm = xm;
            })
        }

        function initFieldConfigData(data, tableNo) {
            data.forEach(function (item) {
                item.tableNo = tableNo;
                if(item.showInForm == undefined){
                    item.showInForm = true;
                }
                if(item.showInSearchForm == undefined){
                    item.showInSearchForm = true;
                }
                if(item.showInList == undefined){
                    item.showInList = true;
                }
                if(item.isTitle == undefined){
                    item.isTitle = item.field_key.indexOf("_name") > 0 || item.field_key.indexOf("_title") > 0;
                }
                if(item.isRequired == undefined){
                    item.isRequired = item.is_nullable == 1 ? false : true;
                }
            })
            return data;
        }

        function renderTableReleaseConfig(data) {
            if (Object.keys(tableFields).length > 1) {
                // 渲染关联字段模板
                let releaseFieldTemp = $('#release_field_templet').clone();
                let selectHtml = "<select name=\"release_field_{{d.no}}\" lay-verify=\"required\" >"
                selectHtml += '<option value="">选择关联字段</option>'
                Object.keys(tableFields).forEach(function (no) {
                    tableFields[no].forEach(function (item) {
                        let optionValue = no + '.' + item.field_key;
                        selectHtml += '<option  {{d.releaseFieldNo == "' + optionValue + '"?"selected":"" }} value="' + optionValue + '">表' + no + '.' + item.field_name + '(' + item.field_key + ')</option>';
                    })
                })
                selectHtml += "</select>";
                releaseFieldTemp.text(selectHtml);
                let releaseField1TempHtml = releaseFieldTemp.show().prop("outerHTML").replace(/release_field/g, 'release_field1').replace(/releaseFieldNo/g, 'releaseField1');
                let releaseField2TempHtml = releaseFieldTemp.show().prop("outerHTML").replace(/release_field/g, 'release_field2').replace(/releaseFieldNo/g, 'releaseField2');
                $('#release_field_templet_area').html(releaseField1TempHtml + releaseField2TempHtml);
                // 渲染关联字段配置表格组件
                renderReleaseTableTable(data);
            } else {
                $("#table_release_dyn_area").html("");
            }
        }

        function renderReleaseTableTable(data) {
            if (!data || data.length <= 0) {
                data = [{}]
            }
            // 重新设置排序号
            data.forEach((item, idx) => item.no = idx + 1);
            let html = $("#table_release_config_temp").clone().html();
            $("#table_release_dyn_area").html(html.replace(/_temp/g, ''));
            // 渲染组件
            table.render({
                id: "table_release_list",
                elem: "#table_release_list",
                data: data,
                cols: tableReleaseCols,
                limit: 999,
            })
            table.on("tool(table_release_list)", releaseEventListener);
        }

        // 添加表格数据
        function addTableData(tableData, preData) {
            let newTableData = [];
            let isAdd = false;
            for (let i = 0; i < tableData.length; i++) {
                newTableData.push(tableData[i]);
                if (preData != null) {
                    if (preData.no == tableData[i].no) {
                        newTableData.push({})
                        isAdd = true;
                    }
                }
            }
            if (!isAdd) {
                newTableData.push({})
            }
            return newTableData;
        }

        // 删除表格数据
        function removeTableData(tableData, data) {
            let newTableData = [];
            for (let i = 0; i < tableData.length; i++) {
                if (data != null) {
                    if (data.no == tableData[i].no) {
                        continue;
                    }
                }
                newTableData.push(tableData[i]);
            }
            return newTableData;
        }


        // 事件监听
        function releaseEventListener(obj) {
            let event = obj.event;
            let data = obj.data;
            switch (event) {
                case 'add':
                    renderReleaseTableTable(addTableData(getReleaseTableList(), data));
                    break;
                case 'del':
                    renderReleaseTableTable(removeTableData(getReleaseTableList(), data));
                    break;
            }
        }

        function getReleaseTableList() {
            let formVals = form.val("generator_model-edit-form");
            let list = [];
            Object.keys(formVals).forEach(function (key) {
                if (key.indexOf("release_field1_") >= 0) {
                    let no = key.substring(15);
                    list.push({
                        releaseField1: formVals[key],
                        releaseField2: formVals["release_field2_" + no],
                        no: no,
                    })
                }
            })
            list = list.sort(function (a, b) {
                return a.no - b.no
            })
            return list;
        }

        function parseSaveData(formVals) {
            let data = {};
            data.generator_id = formVals.generator_id;
            data.generator_name = formVals.generator_name;
            let templateSelect = formVals.template_select;
            data.template_id =templateSelect;
            let config = {};
            config.ctlUri = formVals.controller_uri;
            config.packagePath = formVals.code_package;
            // 模板值获取
            tempList.forEach(function (item) {
                if (item.template_id == templateSelect) {
                    config.template = {attrs: item};
                    config.template.attrs.template_config = parseTempConfig(formVals, config.template.attrs.template_config);
                }
            })
            // 关联表值获取
            config.tables = [];
            config.template = config.template?config.template:{};
            config.template.attrs = config.template.attrs?config.template.attrs:{};
            for (let idx = 0; idx < config.template.attrs.table_require_count; idx++) {
                let tableSelect = formVals['table' + (idx + 1)]
                let tableFieldList = tableFields[idx + 1] || [];
                let tableList = tables['table' + (idx + 1) + '_select'];
                let tableAttrs;
                tableList.forEach(function (item) {
                    if (item.table_id == tableSelect) {
                        tableAttrs = item;
                    }
                })
                config.tables[idx] = {
                    attrs: tableAttrs,
                    fieldModelList: []
                }
                let tableTitle = formVals['title_' + (idx + 1)]
                tableFieldList.forEach(function (item) {
                    let checkValue = xmSelect.get('#checker_' + (idx + 1) + '_' + item.field_id, true).getValue();
                    let checkers = [];
                    checkValue.forEach(function(ck){
                        checkers.push(ck.value);
                    })

                    config.tables[idx].fieldModelList.push({
                        attrs: item,
                        isTitle: tableTitle == item.field_id,
                        showInForm: formVals['show_in_form_' + (idx + 1) + '_' + item.field_id] == 'on',
                        showInSearchForm: formVals['show_in_search_form_' + (idx + 1) + '_' + item.field_id] == 'on',
                        showInList: formVals['show_in_list_' + (idx + 1) + '_' + item.field_id] == 'on',
                        searchMethod: formVals['search_method_' + (idx + 1) + '_' + item.field_id],
                        formComponent: formVals['form_component_' + (idx + 1) + '_' + item.field_id],
                        formOrder: formVals['form_order_' + (idx + 1) + '_' + item.field_id],
                        isRequired: formVals['required_' + (idx + 1) + '_' + item.field_id] == 'on',
                        checkers: checkers,
                    })
                })
            }
            // 表关联关系值获取
            config.releaseFieldsList = getReleaseTableList();
            data.generator_config = JSON.stringify(config)
            return data;
        }

        function parseTempConfig(formVals, config){
            config = config?JSON.parse(config):[];
            if(config.length>0){
                Object.keys(formVals).forEach(function(key){
                    if(key.indexOf("temp_param_") == 0){
                        let name = key.substring(11);
                        for(let idx = 0; idx < config.length; idx++){
                            if(config[idx].name == name) {
                                config[idx].value = formVals[key];
                            }
                        }
                    }
                });
            }
            return JSON.stringify(config)
        }


        /* 监听提交 */
        let generatorFormSubmit = function (data) {
            layer.msg('正在保存中，请稍候', {icon: 16});
            // parseSaveData(data.field);
            $.ajax({
                method: 'post',
                url: "/generator/code/save",
                data: parseSaveData(data.field),
                dataType: 'json',
                success: function (rs) {
                    if (rs.success) {
                        layer.msg(rs.message || '保存成功', {icon: 6});
                        let config = #(detail.generator_id == null ? '{page: {curr: 1}}' : '{}');
                        #if(isStepNav)
                        templateNav.doStepNavCallback({success: true, gid: rs.gid})
                        #else
                        table.reload('generator_model-table', config);
                        layer.closeAll('page'); //关闭所有页面层
                        #end
                    } else {
                        #if(isStepNav)
                        templateNav.doStepNavCallback({success: false})
                        #end
                        layer.msg('保存失败,' + rs.message || '保存失败', {icon: 5});
                    }
                },
                error: function (a, b, c) {
                    layer.msg('请求异常，保存失败', {icon: 5});
                }
            });
            return false;
        };
        form.on('submit(btn-generator_model-submit)', generatorFormSubmit);
        /* 监听取消 */
        $("[lay-filter=btn-generator_model-cancle]").click(function () {
            layer.closeAll("page");
        });
    });
</script>